//
//  RWAddAddressViewController.m
//  RedWine
//
//  Created by Liufangfang on 2017/1/14.
//  Copyright © 2017年 HuiBangKe. All rights reserved.
//

#import "RWAddAddressViewController.h"
#import "FTYInfoVertifyTools.h"

@interface RWAddAddressViewController ()<UITextFieldDelegate>{
    
    NSArray *cellTitles;
    NSArray *textFields;
    BOOL isDefaultAddr;
}

@property (nonatomic, strong) UITextField *receiveTF;
@property (nonatomic, strong) UITextField *phoneNumTF;
@property (nonatomic, strong) UITextField *areaTF;
@property (nonatomic, strong) UITextField *detailAddrTF;
@property (nonatomic, strong) UITextField *postCodeTF;
@property (nonatomic, strong) UISwitch *pushST;

@end

@implementation RWAddAddressViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    [self setNavigation];
    [self setAddAddressUI];
    [self loadDatas];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{

    cellTitles = @[@"收货人：", @"手机号码：", @"省/市/区：", @"详细地址：", @"邮编：", @"设为默认地址（每次默认使用该地址）"];
    textFields = @[@"姓名", @"手机号", @"省/市/区", @"详细地址", @"邮编"];
    isDefaultAddr = NO;
}

- (void)loadDatas{
    
    if (self.mAddressModel) {
        
        _receiveTF.text = _mAddressModel.true_name;
        _phoneNumTF.text = _mAddressModel.mob_phone;
        _areaTF.text = _mAddressModel.area_info;
        _detailAddrTF.text = _mAddressModel.address;
        _postCodeTF.text = _mAddressModel.post_code;
        [_saveAddrBtn setTitle:@"保存修改地址" forState:UIControlStateNormal];
    }
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = @"添加收货地址";
}

- (void)setAddAddressUI{
    
    _addAddressTV = [[FTYTouchTableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_addAddressTV];
    _addAddressTV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _addAddressTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _addAddressTV.scrollEnabled = NO;
    _addAddressTV.dataSource = self;
    _addAddressTV.delegate = self;
    _addAddressTV.touchDelegate = self;
    _addAddressTV.tableFooterView = [self setFooterUI];
}

#pragma mark - Config Invoke Methods

- (UIView *)setFooterUI{
    
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT)];
    
    _saveAddrBtn = [FTYButton createButtonWithTitle:@"保存新增地址" tColor:[UIColor blackColor] fontSize:15.*FTY_WIDTH_BASE backGroundColor:[FTYColor getMainColorWithAlpha:1.] cornerRadius:15.*FTY_WIDTH_BASE];
    [footerV addSubview:_saveAddrBtn];
    [_saveAddrBtn addTarget:self action:@selector(saveAddrBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_saveAddrBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(40.*FTY_HEIGHT_BASE);
        make.left.mas_equalTo(10.*FTY_WIDTH_BASE);
        make.width.mas_equalTo(FTY_SCREEN_WIDTH - 15.*FTY_WIDTH_BASE *2);
        make.height.mas_equalTo(40.*FTY_HEIGHT_BASE);
    }];
    
    return footerV;
}

#pragma mark - Notificaiton Method

#pragma mark - Notificaiton Invoke Methods

#pragma mark - <UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60.*FTY_HEIGHT_BASE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * const addAddressID = @"addAddressID";
    UITableViewCell *addAddressCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addAddressID];
    addAddressCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSInteger row = indexPath.row;
    addAddressCell.textLabel.text = cellTitles[row];
    addAddressCell.textLabel.font = FTY_FONTTSIZE(15);
    
    if (5 != row) {

        UITextField *textField = [[UITextField alloc] init];
        [addAddressCell addSubview:textField];
        textField.placeholder = textFields[row];
        textField.font = FTY_FONTTSIZE(15);
        textField.textColor = [FTYColor grayColor];
        textField.delegate = self;
        [textField sizeToFit];
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(addAddressCell);
            make.left.mas_equalTo(90.*FTY_WIDTH_BASE);
            make.right.mas_offset(-10.*FTY_WIDTH_BASE);
            make.height.mas_equalTo(addAddressCell.mas_height);
        }];
    
        switch (row) {
            case 0:
                _receiveTF = textField;
                break;
            case 1:
                textField.keyboardType = UIKeyboardTypeNumberPad;
                _phoneNumTF = textField;
                break;
            case 2:
                _areaTF = textField;
                break;
            case 3:
                _detailAddrTF = textField;
                break;
            case 4:
                textField.keyboardType = UIKeyboardTypeNumberPad;
                _postCodeTF = textField;
                break;
                
            default:
                break;
            }
    } else {
        
        _pushST = [[UISwitch alloc] initWithFrame:CGRectMake(FTY_SCREEN_WIDTH - 70*FTY_WIDTH_BASE, (CGRectGetHeight(addAddressCell.frame) - 20.*FTY_HEIGHT_BASE)/2, 60*FTY_WIDTH_BASE, 20*FTY_HEIGHT_BASE)];
        [addAddressCell addSubview:_pushST];
        //默认时颜色
        _pushST.backgroundColor = [FTYColor getColor:@"e2e2e2" andAlpha:1.];
        _pushST.layer.masksToBounds = YES;
        _pushST.layer.cornerRadius = _pushST.bounds.size.height/2;
        //边缘颜色
        _pushST.tintColor = [FTYColor getColor:@"e2e2e2" andAlpha:1.];
        //开启时颜色
        _pushST.onTintColor = [FTYColor getColor:@"32cd00" andAlpha:1.];
        [_pushST addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];
    }

    //底部线
    UIView *line = [[UIView alloc] init];
    [addAddressCell addSubview:line];
    line.backgroundColor = [UIColor lightGrayColor];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
        make.height.mas_offset(.5*FTY_HEIGHT_BASE);
    }];
    [self loadDatas];
    return addAddressCell;
}

#pragma mark - <UITableViewDelegate>

#pragma mark - <FTYTouchTableViewDelegate>

- (void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [_receiveTF resignFirstResponder];
    [_phoneNumTF resignFirstResponder];
    [_areaTF resignFirstResponder];
    [_detailAddrTF resignFirstResponder];
    [_postCodeTF resignFirstResponder];
}

#pragma mark - <UITextFieldDelegate>

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [_receiveTF resignFirstResponder];
    [_phoneNumTF resignFirstResponder];
    [_areaTF resignFirstResponder];
    [_detailAddrTF resignFirstResponder];
    [_postCodeTF resignFirstResponder];
    
    return YES;
}

#pragma mark - Private Invoke Methods

- (void)pushAction:(UISwitch *)st{

    if (st.on) {
        isDefaultAddr = YES;
    } else {
        isDefaultAddr = NO;
    }
}

- (void)saveAddrBtnAction:(UIButton *)btn{
    
    NSString *receive = _receiveTF.text;
    NSString *phoneNum = _phoneNumTF.text;
    NSString *area = _areaTF.text;
    NSString *detailAddr = _detailAddrTF.text;
    NSString *postCode = _postCodeTF.text;
    
    if ([FTYInfoVertifyTools isnilVertify:receive]) {
        [[FTYToastView alloc] addTitle:@"收货人不能为空～" addView:self.view];
    } else if([FTYInfoVertifyTools isnilVertify:phoneNum]){
        [[FTYToastView alloc] addTitle:@"手机号码不能为空～" addView:self.view];
    }  else if([FTYInfoVertifyTools isnilVertify:area]){
        [[FTYToastView alloc] addTitle:@"区域不能为空～" addView:self.view];
    } else if([FTYInfoVertifyTools isnilVertify:detailAddr]){
        [[FTYToastView alloc] addTitle:@"请填写详细地址～" addView:self.view];
    } else {
        
        FTYUser *user = [FTYUser sharedUser];
        NSString *op;
        if (_mAddressModel) {
            op = [NSString stringWithFormat:@"updateaddr"];
        }else{
            op = [NSString stringWithFormat:@"newaddress"];
        }
//        [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=newaddress&member_id=%@&token=%@&true_name=%@&area_info=%@&mob_phone=%@&is_default=%@", user.userID, user.userToken, receive, detailAddr, phoneNum, [NSNumber numberWithBool:isDefaultAddr]] parameters:nil block:^(id result, NSError *error) {
        [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=%@&member_id=%@&token=%@&true_name=%@&area_info=%@&address=%@&&mob_phone=%@&is_default=%@&address_id=%@",op, user.userID, user.userToken, receive, area,detailAddr, phoneNum, [NSNumber numberWithBool:isDefaultAddr],_mAddressModel.address_id] parameters:nil block:^(id result, NSError *error) {
            if (!error) {
                
                NSInteger code = [[[result objectForKey:@"err"] objectForKey:@"errorcode"] integerValue];
                NSString *info = [[result objectForKey:@"err"] objectForKey:@"errorinfo"];
                if (0 == code) {
                    [self saveAddrSuccess];
                } else {
                    [[FTYToastView alloc] addTitle:info addView:self.view];
                }
            } else {
                
                NSLog(@"====%@", error);
            }
        }];
    }
}

- (void)saveAddrSuccess{
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"ModifyPasswordSuccessNotification" object:nil];
    //[self.navigationController popToRootViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:YES];
    
}

@end
